﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Lucene.Net.Search;
using Lucene.Net.Highlight;
using Lucene.Net.Analysis.Standard;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.Analysis.China;
using Lucene.Net.QueryParsers;
using Lucene.Net.Store;


namespace ASPNETX
{
    public class Searcher
    {
        private IndexSearcher searcher;

        public Searcher(string indexfilesloaction)
        {
            string path = indexfilesloaction;
            
            FSDirectory dir = FSDirectory.GetDirectory(path,false);

            searcher=new IndexSearcher(dir);
        }

        public DataTable GetResult(string searchcontent)
        {
            DataTable result = new DataTable();

            result.Columns.Add("path");
            result.Columns.Add("content");
            result.Columns.Add("title");
            
            Hits myHits;
            
            QueryParser myParser = new QueryParser("Content", new ChineseAnalyzer());
            Query myQuery = myParser.Parse(searchcontent);

            myHits = searcher.Search(myQuery);

            Highlighter highlighter;
            
            Lucene.Net.Highlight.Formatter fm = new SimpleHTMLFormatter("<span style=\"color:red;font-weight:bold\">", "</span>");
            highlighter = new Highlighter(fm, new QueryScorer(myQuery));
            highlighter.SetTextFragmenter(new SimpleFragmenter(100));
            
            for (int i = 0; i < myHits.Length(); i++)
            {
                DataRow dtrow = result.NewRow();

                dtrow["path"] = myHits.Doc(i).Get("Path");

                string content = myHits.Doc(i).Get("Content");
                Lucene.Net.Analysis.TokenStream tokenStream = new ChineseAnalyzer().TokenStream("Content", new System.IO.StringReader(content));
                dtrow["content"] = highlighter.GetBestFragments(tokenStream, content, 0, "...");

                dtrow["title"] = myHits.Doc(i).Get("Title");

                result.Rows.Add(dtrow);
            }

            return result;
        }
    }
}
